package com.hornsun.constant;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ${曹文成} on 2016/7/30 0030.
 */
public class AbstractError {
    public static final AbstractError SUCCESS = new AbstractError(0, "操作成功");
    public static final AbstractError RE_UPLOAD = new AbstractError(96, "文件已经上传");
    public static final AbstractError LOCAL_FILE_NOTEXISTED = new AbstractError(97, "本地文件不存在");
    public static final AbstractError DATABASE_OPERATE_FAILED = new AbstractError(98, "数据库操作失败");
    public static final AbstractError RECORD_EMPTY = new AbstractError(99, "数据库记录为空");
    public static final AbstractError INNER_ERROR = new AbstractError(100, "系统内部错误");
    private static final Map<Integer, AbstractError> ERRORCODE_ENUM = new HashMap<>();
    private Integer errorCode;
    private String errorInfo;


    public AbstractError(Integer errorCode, String errorInfo) {
        this.errorCode = errorCode;
        this.errorInfo = errorInfo;
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public String getErrorInfo() {
        return errorInfo;
    }

    protected static AbstractError getEnumByErrorCode(Integer errorCode) {
        if (ERRORCODE_ENUM.containsKey(errorCode)) {
            return ERRORCODE_ENUM.get(errorCode);
        }
        return null;
    }

    protected static void putChildEnumIntoMap(Class<? extends AbstractError> clazz) {
        for (Field field : clazz.getFields()) {
            try {
                if (field.getType().equals(AbstractError.class)) {
                    AbstractError cc = (AbstractError) field.get(clazz);
                    if (!ERRORCODE_ENUM.containsKey(cc.getErrorCode())) {
                        ERRORCODE_ENUM.put(cc.getErrorCode(), cc);
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
